#include "paymentprocessor.h"
#include <QDateTime>
#include <QDebug>
#include <QThread>
#include <QRandomGenerator>

PaymentProcessor::PaymentProcessor(QObject *parent)
    : QObject(parent), m_memberDAO(nullptr)
{
}

void PaymentProcessor::setMemberDAO(MemberDAO *memberDAO)
{
    m_memberDAO = memberDAO;
}

bool PaymentProcessor::processPayment(int orderId, PaymentMethod method, double amount,
                                    const QString &transactionNo, int customerId)
{
    m_paymentResult.clear();

    bool success = false;
    QString processedTransactionNo = transactionNo;

    if (processedTransactionNo.isEmpty()) {
        processedTransactionNo = generateTransactionNo(method);
    }

    switch (method) {
    case PAYMENT_CASH:
        success = processCashPayment(orderId, amount);
        break;
    case PAYMENT_CARD:
        success = processCardPayment(orderId, amount, processedTransactionNo);
        break;
    case PAYMENT_WECHAT:
        success = processWechatPayment(orderId, amount, processedTransactionNo);
        break;
    case PAYMENT_ALIPAY:
        success = processAlipayPayment(orderId, amount, processedTransactionNo);
        break;
    case PAYMENT_MEMBER_BALANCE:
        if (customerId == 0) {
            emit errorOccurred("会员ID不能为空");
            return false;
        }
        success = processMemberBalancePayment(orderId, amount, customerId);
        break;
    default:
        emit errorOccurred("不支持的支付方式");
        return false;
    }

    // 记录支付日志
    logPayment(orderId, method, amount, processedTransactionNo, success);

    if (success) {
        m_paymentResult["orderId"] = orderId;
        m_paymentResult["method"] = static_cast<int>(method);
        m_paymentResult["methodName"] = getPaymentMethodName(method);
        m_paymentResult["amount"] = amount;
        m_paymentResult["transactionNo"] = processedTransactionNo;
        m_paymentResult["timestamp"] = QDateTime::currentDateTime();
        m_paymentResult["success"] = true;

        emit paymentCompleted(orderId, true, "支付成功");
    } else {
        emit paymentCompleted(orderId, false, "支付失败");
    }

    return success;
}

bool PaymentProcessor::processRefund(int orderId, const QString &reason)
{
    qDebug() << "处理退款，订单ID:" << orderId << "原因:" << reason;

    QThread::sleep(1);

    emit refundCompleted(orderId, true, "退款成功");
    return true;
}

QString PaymentProcessor::getPaymentMethodName(PaymentMethod method)
{
    switch (method) {
    case PAYMENT_CASH: return "现金支付";
    case PAYMENT_CARD: return "银行卡支付";
    case PAYMENT_WECHAT: return "微信支付";
    case PAYMENT_ALIPAY: return "支付宝支付";
    case PAYMENT_MEMBER_BALANCE: return "会员余额支付";
    default: return "未知支付方式";
    }
}

QMap<int, QString> PaymentProcessor::getAllPaymentMethods()
{
    QMap<int, QString> methods;
    methods[PAYMENT_CASH] = "现金支付";
    methods[PAYMENT_CARD] = "银行卡支付";
    methods[PAYMENT_WECHAT] = "微信支付";
    methods[PAYMENT_ALIPAY] = "支付宝支付";
    methods[PAYMENT_MEMBER_BALANCE] = "会员余额支付";
    return methods;
}

bool PaymentProcessor::isPaymentMethodAvailable(PaymentMethod method, int customerId)
{
    switch (method) {
    case PAYMENT_MEMBER_BALANCE: {  // 这里添加左大括号，开始作用域
        if (customerId == 0) return false;
        if (!m_memberDAO) return false;

        // 检查会员余额是否足够
        QMap<QString, QVariant> memberInfo = m_memberDAO->getMemberById(customerId);
        if (memberInfo.isEmpty()) return false;

        double balance = memberInfo["balance"].toDouble();
        // 这里需要知道订单金额，但由于是通用检查，我们假设有足够余额
        return balance > 0;
    }  // 这里添加右大括号，结束当前case的作用域
    default:
        return true; // 其他支付方式默认可用
    }
}

QMap<QString, QVariant> PaymentProcessor::getPaymentResult() const
{
    return m_paymentResult;
}

bool PaymentProcessor::processCashPayment(int orderId, double amount)
{
    qDebug() << "现金支付处理，订单ID:" << orderId << "金额:" << amount;
    return true;
}

bool PaymentProcessor::processCardPayment(int orderId, double amount, const QString &transactionNo)
{
    qDebug() << "银行卡支付处理，订单ID:" << orderId << "金额:" << amount << "交易号:" << transactionNo;

    QThread::sleep(2);
    return true;
}

bool PaymentProcessor::processWechatPayment(int orderId, double amount, const QString &transactionNo)
{
    qDebug() << "微信支付处理，订单ID:" << orderId << "金额:" << amount << "交易号:" << transactionNo;

    QThread::sleep(2);
    return true;
}

bool PaymentProcessor::processAlipayPayment(int orderId, double amount, const QString &transactionNo)
{
    qDebug() << "支付宝支付处理，订单ID:" << orderId << "金额:" << amount << "交易号:" << transactionNo;

    QThread::sleep(2);
    return true;
}

/**
 * 会员余额支付处理算法
 * 业务逻辑：
 * 1. 验证会员DAO是否已设置
 * 2. 根据会员ID查询会员信息，验证会员是否存在
 * 3. 检查会员余额是否足够支付订单金额
 * 4. 执行余额扣除操作，确保数据一致性
 * 5. 记录支付日志
 * 
 * @param orderId 订单ID
 * @param amount 支付金额
 * @param customerId 会员ID
 * @return 支付是否成功
 */
bool PaymentProcessor::processMemberBalancePayment(int orderId, double amount, int customerId)
{
    if (!m_memberDAO) {
        emit errorOccurred("会员DAO未设置");
        return false;
    }

    // 检查会员余额是否足够
    QMap<QString, QVariant> memberInfo = m_memberDAO->getMemberById(customerId);
    if (memberInfo.isEmpty()) {
        emit errorOccurred("会员不存在");
        return false;
    }

    double balance = memberInfo["balance"].toDouble();
    if (balance < amount) {
        emit errorOccurred("会员余额不足");
        return false;
    }

    // 扣除会员余额
    if (!m_memberDAO->deductBalance(customerId, amount)) {
        emit errorOccurred("扣除会员余额失败");
        return false;
    }

    qDebug() << "会员余额支付处理，订单ID:" << orderId << "金额:" << amount << "会员ID:" << customerId;
    return true;
}

QString PaymentProcessor::generateTransactionNo(PaymentMethod method)
{
    QString prefix;
    switch (method) {
    case PAYMENT_CASH: prefix = "CASH"; break;
    case PAYMENT_CARD: prefix = "CARD"; break;
    case PAYMENT_WECHAT: prefix = "WECHAT"; break;
    case PAYMENT_ALIPAY: prefix = "ALIPAY"; break;
    case PAYMENT_MEMBER_BALANCE: prefix = "MEMBER"; break;
    default: prefix = "UNKNOWN"; break;
    }

    QDateTime now = QDateTime::currentDateTime();
    QString timestamp = now.toString("yyyyMMddHHmmsszzz");
    int random = QRandomGenerator::global()->bounded(1000, 9999);

    return QString("%1_%2_%3").arg(prefix).arg(timestamp).arg(random);
}

void PaymentProcessor::logPayment(int orderId, PaymentMethod method, double amount,
                                const QString &transactionNo, bool success)
{
    qDebug() << "支付日志 - 订单ID:" << orderId
             << "支付方式:" << getPaymentMethodName(method)
             << "金额:" << amount
             << "交易号:" << transactionNo
             << "状态:" << (success ? "成功" : "失败");
}
